using Avalonia.Controls;
using DesktopApp.ViewModels;
using Avalonia.Input.Platform;
using Avalonia.Input;
using Avalonia.VisualTree;
using DesktopApp.Views.Controls;
using System.Linq;
using Avalonia.Platform.Storage;
using Avalonia.Interactivity;
using System.Threading.Tasks;
using System;
using Avalonia.Reactive;
using System.Reactive.Linq;
using Avalonia;
using Avalonia.Threading;
using Avalonia.ReactiveUI;
using System.Diagnostics;
using CommunityToolkit.Mvvm.Input;

namespace DesktopApp;

public partial class MainWindow : Window
{
    // Add public parameterless constructor for XAML loader/designer
    public MainWindow()
    {
        InitializeComponent();
        #if DEBUG
        // This is a common pattern to attach the design-time DataContext
        // Make sure your ViewModel has a parameterless constructor or
        // use a Design-Time ViewModel approach if needed.
        // this.DataContext = new MainWindowViewModel(); // Example: Only if MainWindowViewModel has paramless ctor
        #endif
    }

    public MainWindow(MainWindowViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
    }

    // --- Drag Drop Logic ---
    private void RulesItemsControl_DragOver(object? sender, DragEventArgs e)
    {
        // Allow drop only if the data is in the expected format
        if (e.Data.Contains(RuleItemView.RuleItemDragFormat))
        {
            e.DragEffects = DragDropEffects.Move;
        }
        else
        {
            e.DragEffects = DragDropEffects.None;
        }
        e.Handled = true;
    }

    private void RulesItemsControl_Drop(object? sender, DragEventArgs e)
    {
        if (e.Data.Get(RuleItemView.RuleItemDragFormat) is RuleItemViewModel sourceRule &&
            DataContext is MainWindowViewModel shellViewModel && // Get the Shell VM
            shellViewModel.RulesVm is RulesViewModel rulesViewModel && // Get the Rules VM from Shell
            sender is ScrollViewer scrollViewer)
        {
            var dropPosition = e.GetPosition(scrollViewer);

            var outerItemsControl = scrollViewer.FindDescendantOfType<ItemsControl>();
            if (outerItemsControl == null)
            {
                Debug.WriteLine("Drop failed: Could not find RulesItemsControl.");
                e.Handled = true;
                return;
            }

            RuleItemViewModel? targetRule = null;
            bool dropBefore = false;
            Control? targetContainer = null;

            foreach (var groupContainer in outerItemsControl.GetVisualChildren().OfType<Panel>())
            {
                var innerItemsControl = groupContainer.FindDescendantOfType<ItemsControl>();
                if (innerItemsControl == null) continue;

                foreach (var itemContainer in innerItemsControl.GetVisualChildren().OfType<Control>())
                {
                    var boundsInScrollViewer = itemContainer.Bounds;
                    var transform = itemContainer.TransformToVisual(scrollViewer);
                    if (transform.HasValue)
                    {
                        var transformedBounds = boundsInScrollViewer.TransformToAABB(transform.Value);
                        if (transformedBounds.Contains(dropPosition))
                        {
                            var positionInItem = e.GetPosition(itemContainer);
                            dropBefore = positionInItem.Y < itemContainer.Bounds.Height / 2;
                            targetRule = itemContainer.DataContext as RuleItemViewModel;
                            targetContainer = itemContainer;
                            Debug.WriteLine($"Drop target found: {targetRule?.Name}, DropBefore: {dropBefore}");
                            goto FoundTarget;
                        }
                    }
                    else
                    {
                         Debug.WriteLine($"Warning: Could not get transform for item container {itemContainer.DataContext}");
                    }
                }
            }

        FoundTarget:

            if (targetRule != null && targetContainer != null)
            {
                if (targetRule == sourceRule)
                {
                     Debug.WriteLine("Drop cancelled: source is target.");
                }
                else
                {
                    // Use the overload that takes ViewModels and dropBefore flag
                    rulesViewModel.MoveRule(sourceRule, targetRule, dropBefore); // Call MoveRule on RulesViewModel
                    Debug.WriteLine($"Drop completed. Target: {targetRule.Name}, DropBefore: {dropBefore}");
                }
            }
            else
            {
                // Dropped in empty space, move to end of the entire list
                 rulesViewModel.MoveRule(sourceRule, null, false); // Call MoveRule on RulesViewModel
                 Debug.WriteLine("Drop completed: Moved to end (no specific target found).");
            }

            e.Handled = true;
        }
        else
        {
            Debug.WriteLine("Drop failed: Invalid data format, ViewModel, or Sender type.");
            e.Handled = true;
        }
    }

    // --- Custom Title Bar Event Handlers --- // Moved to TitleBarControl.axaml.cs

    // private void TitleBar_PointerPressed(object? sender, PointerPressedEventArgs e)
    // {
    //     // Allow dragging the window
    //     this.BeginMoveDrag(e);
    // }
    //
    // private void MinimizeButton_Click(object? sender, RoutedEventArgs e)
    // {
    //     this.WindowState = WindowState.Minimized;
    // }
    //
    // private void MaximizeRestoreButton_Click(object? sender, RoutedEventArgs e)
    // {
    //     this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
    //     // TODO: Optionally change the icon between Maximize and Restore
    //     // var icon = this.FindControl<MaterialIcon>("MaximizeRestoreIcon");
    //     // if (icon != null)
    //     // {
    //     //     icon.Kind = this.WindowState == WindowState.Maximized ? MaterialIconKind.WindowRestore : MaterialIconKind.WindowMaximize;
    //     // }
    // }
    //
    // private void CloseButton_Click(object? sender, RoutedEventArgs e)
    // {
    //     this.Close();
    // }
}